package gob.cgr.web.sgrh.servlet;


import gob.cgr.web.sgrh.managed.UsuarioMB;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
      //  System.out.println("capturando la session: "+session);
        
        
        Object user=session==null?null: session.getAttribute("usuarioMB");
        if (user == null || ((UsuarioMB)user).getUser() == null) {
        	String target=request.getContextPath() + "/login.jsf";
        	
        	if(isAJAXRequest(request)){
        	   	   	managedAJAXRequest(response,target);
             }
        	else{
        		  response.sendRedirect(target); // Usuario no logueado, directo al login.
        		
        	}
        	
          
        } else {
            chain.doFilter(req, res); // usuario logueado, pase usted.
        }
        
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	private void managedAJAXRequest(HttpServletResponse response,String target)throws IOException, ServletException{
		StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><partial-response><redirect url=\"").append(target).append("\"></redirect></partial-response>");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        System.out.println("salida :"+sb.toString());
        PrintWriter pw = response.getWriter();
        pw.println(sb.toString());
        pw.flush();
		
	}
	
	
	private boolean isAJAXRequest(HttpServletRequest request) {
	    boolean check = false;
	    String facesRequest = request.getHeader("Faces-Request");
	    if (facesRequest != null && facesRequest.equals("partial/ajax")) {
	        check = true;
	    }
	    return check;
	}
	
}
